package com.pagepub.core.utils;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.pagepub.core.exception.ExceptionMessageParam;
import com.pagepub.core.exception.SysException;

public class StringUtil {
	public final static String SWAPTYPE_SET = "set";
	public final static String SWAPTYPE_GET = "get";
	public StringUtil()
	{
	}
	
	
	/**
	 * String类型转换成int类型
	 * @param str 字符串

	 * @return int 返回转换后的类型
	 */
	public static int stringToInt(String str) 
	{
		int i = 0;
		if (str != null) 
		{
			try 
			{
				i = Integer.parseInt(str.trim());
			} 
			catch (Exception e) 
			{
				return i;
			}
		} 

		return i;
	}

	/**
	 * String类型转换成long类型
	 * @param str 字符串

	 * @return long 返回转换后的类型
	 */
	public static long stringToLong(String str) 
	{
		Long d = new Long(0);
		try 
		{
			d = Long.valueOf(str);
		} 
		catch (Exception e) 
		{
			return d.longValue();
		}

		return d.longValue();
	}

	
	public static String getIP(HttpServletRequest request)
	   {
	     String ip="";
	     if(request.getHeader("X-Forwarded-For")!=null)
	       ip=request.getHeader("X-Forwarded-For");
	     else ip=request.getRemoteAddr();
	     return ip;
	   }

	
	public static String getUrlencode(String str) {
		String result = "";		
		 result=java.net.URLEncoder.encode(str);
		return result;
	}
	
	public static String getUrldecode(String str) {
		String result = "";
		 result=java.net.URLDecoder.decode(str);
		// String param= new String(request.getParameter("param").getBytes("ISO-8859-1"), "GBK");
		return result;
	}
	
	public static String getRandomFileName() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String prefix = sf.format(new Date());
        Random random = new Random();
        String suffix = "";
        for (int i = 0; i < 6; i ++) {
          suffix += random.nextInt(10);
        }

        return (prefix + suffix);
      }
	public static String getExtension(String fileName) {
	 return fileName.substring(fileName.lastIndexOf(".")+1);
	}
	
	public static boolean isValidFile(String fileName) {
	//	String[] validFiles = { "txt", "gif", "jpg", "jpeg", "jpe", "zip",
	//			"rar", "doc", "ppt", "xls", "html", "htm", "tif", "tiff", "pdf" };
		String[] validFiles = {  "jpg", "jpeg", "jpe",  "mp3", "swf", "flv" };
		boolean ret = false;
		for (int i = 0; i < validFiles.length; i++) {
			if (fileName.toLowerCase().endsWith(validFiles[i])) {
				ret = true;
				break;
			}
		}
		return ret;
	}
	
	public static String getContentType(String fileName) {
		String fileNameTmp = fileName.toLowerCase();
		String ret = "";
		if (fileNameTmp.endsWith("txt")) {
			ret = "text/plain";
		}
		if (fileNameTmp.endsWith("gif")) {
			ret = "image/gif";
		}
		if (fileNameTmp.endsWith("jpg")) {
			ret = "image/jpeg";
		}
		if (fileNameTmp.endsWith("jpeg")) {
			ret = "image/jpeg";
		}
		if (fileNameTmp.endsWith("jpe")) {
			ret = "image/jpeg";
		}
		if (fileNameTmp.endsWith("zip")) {
			ret = "application/zip";
		}
		if (fileNameTmp.endsWith("rar")) {
			ret = "application/rar";
		}
		if (fileNameTmp.endsWith("doc")) {
			ret = "application/msword";
		}
		if (fileNameTmp.endsWith("ppt")) {
			ret = "application/vnd.ms-powerpoint";
		}
		if (fileNameTmp.endsWith("xls")) {
			ret = "application/vnd.ms-excel";
		}
		if (fileNameTmp.endsWith("html")) {
			ret = "text/html";
		}
		if (fileNameTmp.endsWith("htm")) {
			ret = "text/html";
		}
		if (fileNameTmp.endsWith("tif")) {
			ret = "image/tiff";
		}
		if (fileNameTmp.endsWith("tiff")) {
			ret = "image/tiff";
		}
		if (fileNameTmp.endsWith("pdf")) {
			ret = "application/pdf";
		}
		return ret;
	}
	
	//随机提取四位数

	public static String getFourBitRan()
	{
		java.util.Random ran = new java.util.Random();
		String ranNum = String.valueOf(Math.abs(ran.nextInt()));
		while(ranNum.length() != 4)
		{
			if(ranNum.length() >4)
				ranNum = ranNum.substring(0,ranNum.length()-1);
			else
				ranNum = ranNum + "0";
		}
		return ranNum;
	}

	public static long getFileSize(String fileUri,File inf)
	{
		long size = 0;
		File f = null;
		
		if(fileUri!=null)
		{
			f = new File(fileUri);
			inf = f;
		}	
		File flist[] = inf.listFiles();

		for(int i=0;i<flist.length;i++)
		{
			if(flist[i].isDirectory())
				size += getFileSize(null,flist[i]);
			else
				size += flist[i].length();
		}
		
		return size;
	}
	
	public static boolean checkParameter(String para) throws Exception
	{
        int flag = 0;
		boolean bCheckPara=true;
		if(para!=null)
		{
			flag += para.indexOf("'") + 1;
			flag += para.indexOf(";") + 1;
			flag += para.indexOf("1=1") + 1;
			flag += para.indexOf("|") + 1;
			flag += para.indexOf("<") + 1;
			flag += para.indexOf(">") + 1;
			if (flag != 0)
			{	
				bCheckPara=false;
			}
		}
		return bCheckPara;
    }
	
	public static String generateRandomString(int stringLength)
	{
		Random random=new Random();
		int code=random.nextInt(stringLength);
		return code+"";
	}

	/**
	 * 功能：去掉expStr表达式前后的str字符(str有大小写区分)
	 * 
	 * @param expStr
	 *            String 要去掉的表达式

	 * @param str
	 *            Str 指定去掉的字串

	 * @return String 成功返回去掉后的表达式

	 */
	public static String trimChr(String expStr, String str)
	{
		String retu = expStr;
		if (expStr.length() == 0)
		{
			return retu;
		}
		if (retu.substring(0,str.length()).equals(str))
		{
			retu = retu.substring(retu.indexOf(str) + str.length(),retu
					.length());
		}
		if (retu.substring(retu.length() - str.length()).equals(str))
		{
			retu = retu.substring(0,retu.length() - str.length());
		}
		return retu;
	}

	/**
	 * 功能：取得表达式象这样的值如下例子 例子：exp="myName=wzs,myvale=1000";
	 * getValue(exp,"myName=",",")结果等于"wzs"
	 * 
	 * @param exp
	 *            String
	 * @param val
	 *            String
	 * @param splitStr
	 *            String
	 * @return String
	 */
	public static String getValue(String exp, String val, String splitStr)
	{
		if (splitStr.trim().length() == 0)
		{
			return exp;
		}
		else if (val.trim().length() == 0)
		{
			return exp;
		}
		String retu = exp;
		StringTokenizer st = new StringTokenizer(exp,splitStr);
		while (st.hasMoreElements())
		{
			String tmp = st.nextToken();
			if (tmp.indexOf(val) > -1)
			{
				retu = tmp.substring(tmp.indexOf(val
						.substring(val.length() - 1)) + 1);
				break;
			}
		}
		return retu;
	}

	/**
	 * 功能：取得表达式象这样的值如下例子 例子：String
	 * exp="myName=wzs,myvale=1000,myage=29,mysex=男";
	 * getValue(exp,"myage=",",",2[注：这个是从第fromIndex个开始搜索xxx=nnn这个的表达式])结果等于"29"
	 * 
	 * @param exp
	 *            String 取出值的表达
	 * @param val
	 *            String 取出值的标头
	 * @param splitStr
	 *            String 分割字串
	 * @param fromIndex
	 *            int 从exp中的第几个xxx=nn的开始搜索

	 * @return String 成功返回xxx=nn这种形式的nn的值

	 */
	public static String getValue(String exp, String val, String splitStr, int fromIndex)
	{
		if (splitStr.trim().length() == 0)
		{
			return exp;
		}
		else if (val.trim().length() == 0)
		{
			return exp;
		}
		String retu = exp;
		StringTokenizer st = new StringTokenizer(exp,splitStr);
		int i = 0;
		while (st.hasMoreElements())
		{
			String tmp = st.nextToken();
			if (i >= fromIndex)
			{
				if (tmp.indexOf(val) > -1)
				{
					retu = tmp.substring(tmp.indexOf("=") + 1);
					break;
				}
			}
			i++;
		}
		return retu;
	}

	/**
	 * 功能：分割字串成数组(这个是对java中的String.split()做的扩展因为String.split()只支持","其它字符不支持)
	 * 
	 * @param expStr
	 *            String 分割的表达如：

	 * @param splitStr
	 *            String 分割的字符如
	 * @return String[]成功返回一个字串数组 例子：String a="1@2@3";String[]
	 *         as=ExtStr.split(a,"@");结果as[0]="1";as[1]="2"...
	 */
	public static String[] split(String expStr, String splitStr)
	{
		if(expStr==null||expStr.length()==0)
		{
			return null;
		}
		StringTokenizer st = new StringTokenizer(expStr,splitStr);
		String retu[] = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreElements())
		{
			retu[i] = st.nextToken().trim();
			i++;
		}
		return retu;
	}
	/**
	 * 获取vo中的属性值

	 * @param bean
	 * @param propertyName
	 * @return
	 */
	public static Object getBeanPropertyValue(Object bean,String propertyName)
	{
		try
		{
			Class cls=bean.getClass();
			Method m = cls.getMethod(propertyName);
			Object retu = m.invoke(bean);
			return retu;
		}
		catch(Exception e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.getBeanPropertyValue("+bean+","+propertyName+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}
	/**
	 * 功能：查找lObj对象中每个元素包含相同vo对象中的某个属性的值

	 * 
	 * @param lObj
	 *            List 每个元素必需是同一类的vo对象
	 * @param findVoMethodName
	 *            String
	 *            查找属性的vo对象中的方法名称（原要是要填property的名称，但reflcet机制中不能取得private的值才改成调用method）

	 * @param findPropertyValue
	 *            Object 查的值该值只能为（简单类型中的数值类型和Integer,String）

	 * @return int 成功返回list所在的下标值，失败返回-1
	 */
	public static int indexOfVoPropertyValue(List lObj, String findVoMethodName, Object findPropertyValue)
	{
		if (lObj == null || lObj.size() == 0)
		{
			return -1;
		}
		Class cls = null;
		for (int i = 0; i < lObj.size(); i++)
		{
			Object obj = lObj.get(i);
			if (cls == null)
			{
				cls = obj.getClass();
			}
			try
			{
				Method m = cls.getMethod(findVoMethodName);
				Object retu = m.invoke(obj);
				if (retu.toString().equals(findPropertyValue.toString()))
				{
					return i;
				}
			}
			catch (Exception e)
			{				
				ExceptionMessageParam emp=new ExceptionMessageParam();
				emp.setKeyOrMessageText("StringUtil.indexOfVoPropertyValue("+lObj+","+findVoMethodName+","+findPropertyValue+")出错!");
				emp.setMessage(true);
				throw new SysException(emp,e);
			}
		}
		return -1;
	}

	/**
	 * 功能：查找lObj对象中每个元素包含相同vo对象中的某个属性的值

	 * 
	 * @param lObj
	 *            List 每个元素必需是同一类的vo对象
	 * @param findVoMethodName
	 *            String
	 *            查找属性的vo对象中的方法名称（原要是要填property的名称，但reflcet机制中不能取得private的值才改成调用method）

	 * @param findPropertyValue
	 *            Object 查的值该值只能为（简单类型中的数值类型和Integer,String）

	 * @param fromIndex
	 *            int 从lObj对象第fromIndex个查找findVoMethodName属性值为findPropertyValue
	 * @return int 成功返回list所在的下标值，失败返回-1
	 */
	public static int indexOfVoPropertyValue(List lObj, String findVoMethodName, Object findPropertyValue, int fromIndex)
	{
		if (lObj == null || lObj.size() == 0)
		{
			return -1;
		}
		Class cls = null;
		for (int i = 0; i < lObj.size(); i++)
		{
			if (i < fromIndex)
			{
				continue;
			}
			Object obj = lObj.get(i);
			if (cls == null)
			{
				cls = obj.getClass();
			}
			try
			{
				Method m = cls.getMethod(findVoMethodName);
				Object retu = m.invoke(obj);
				if (retu.toString().equals(findPropertyValue.toString()))
				{
					return i;
				}
			}
			catch (Exception e)
			{
				ExceptionMessageParam emp=new ExceptionMessageParam();
				emp.setKeyOrMessageText("StringUtil.indexOfVoPropertyValue("+lObj+","+findVoMethodName+","+findPropertyValue+","+fromIndex+")出错!");
				emp.setMessage(true);
				throw new SysException(emp,e);
			}
		}
		return -1;
	}




	/**
	 * 功能：用md5算法加密str字串
	 * 
	 * @param str
	 *            String 要加密的字串
	 * @return String 成功能返回加密好的字串，失败返回null
	 */
	public static String encrypt_MD5(String str)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b = md.digest(str.getBytes());
			return byte2hex(b);
		}
		catch (NoSuchAlgorithmException e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.encrypt_MD5("+str+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}

	/**
	 * 功能：取得主页的url
	 * 
	 * @return String
	 */
	public static String getHomePageUrl(HttpServletRequest req)
	{
		String retu = req.getScheme() + "://";
		retu += req.getServerName();
		if (req.getServerPort() != 80)
		{
			retu += ":" + req.getServerPort();
		}
		retu += req.getContextPath();
		return retu;
	}

	/**
	 * 功能：获取expstr中有多少个strflag
	 * 
	 * @param expstr
	 *            String
	 * @param strflag
	 *            String
	 * @return int
	 */
	public static int getCountStr(String expstr, String strflag)
	{
		int retu = 0;
		int fromIndex = 0;
		int i = expstr.indexOf(strflag,fromIndex);
		while (i >= 0)
		{
			retu++;
			fromIndex = i + strflag.length();
			i = expstr.indexOf(strflag,fromIndex);
		}
		return retu;
	}

	/**
	 * 功能：生成servlet forward时的绝对路径
	 * 
	 * @param subrootUrl
	 *            String 不包含根目录名称的路径（不充许使用相对路径）
	 * @return String 成功返回一个绝对路径

	 *         例子：假设虚拟的根目录是http://localhost:8080/rootDir,rootDir目录下面有aDir,bDir子目录

	 *         当前servlet处理完一个动作后要

	 *         forward()给bDir下面的一个b.jsp则使用req.getRequestDispatcher(ExtStr.makeServletUrl(req,"bDir/b.jsp"));
	 *         forward()给另一个servlet(otherServlet.do)则使用req.getRequestDispatcher(ExtStr.makeServletUrl(req,"otherServlet.do"));
	 */
	public static String makeServletUrl(HttpServletRequest req, String subrootUrl)
	{
		int cnt = getCountStr(req.getRequestURI(),"/") - 2;
		String retu = "";
		for (int i = 0; i < cnt; i++)
		{
			retu += "../";
		}
		retu += subrootUrl;
		return retu;
	}

	/**
	 * 功能：二行制转字符串
	 * 
	 * @param b
	 *            byte[]
	 * @return String
	 */
	public static String byte2hex(byte[] b)
	{
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++)
		{
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
			{
				hs += "0" + stmp;
			}
			else
			{
				hs += stmp;
			}
		}
		return hs.toLowerCase();
	}

	/**
	 * 功能：把expStr表达式中replStr字串替换成newStr
	 * 
	 * @param expStr
	 *            String
	 * @param replStr
	 *            String
	 * @param newStr
	 *            String
	 * @return String
	 */
	public static String replace(String expStr, String replStr, String newStr)
	{
		StringBuffer butmp = new StringBuffer(expStr);
		int startIndex = butmp.indexOf(replStr);
		int endIndex = startIndex + replStr.length();
		int newStrLen = newStr.length();
		while (startIndex >= 0)
		{
			butmp.replace(startIndex,endIndex,newStr);
			startIndex = butmp.indexOf(replStr,startIndex + newStrLen);
			endIndex = startIndex + replStr.length();
		}
		return butmp.toString();
	}

	/**
	 * 功能：把expStr表达式中replStr字串替换成newStr（replStr可用正则表达式的通配符）
	 * 
	 * @param expStr
	 *            String
	 * @param replStr
	 *            String
	 * @param newStr
	 *            String
	 * @return String 成功返回替换后的字串，失败不做处理

	 */
	public static String replaceRegEx(String expStr, String replStr, String newStr)
	{
		String retu = expStr;
		Pattern p = Pattern.compile(replStr);
		Matcher m = p.matcher(expStr);
		retu = m.replaceAll(newStr);
		return retu;
	}
	/**
	 * 功能：把expStr表达式中replStr字串替换成newStr
	 * 
	 * @param expStr
	 *            String
	 * @param replStr
	 *            String
	 * @param newStr
	 *            String
	 * @param fromIndex
	 *            int 从expStr中的第fromIndex查找替换（fromIndex从0开始）
	 * @return String
	 */
	public static String replace(String expStr, String replStr, String newStr, int fromIndex)
	{
		StringBuffer butmp = new StringBuffer(expStr);
		int startIndex = butmp.indexOf(replStr,fromIndex);
		int endIndex = startIndex + replStr.length();
		int newStrLen = newStr.length();
		while (startIndex >= 0)
		{
			butmp.replace(startIndex,endIndex,newStr);
			startIndex = butmp.indexOf(replStr,startIndex + newStrLen);
			endIndex = startIndex + replStr.length();
		}
		return butmp.toString();
	}

	/**
	 * 功能：把一般字串转成base64字串
	 * 
	 * @param str
	 *            String
	 * @return String 成功把str转换成base64编码,失败返回null
	 */
	public static String string2Base64(String str)
	{
		if (str.length() == 0)
		{
			return null;
		}
		BASE64Encoder base64en = new BASE64Encoder();
		String rt=base64en.encodeBuffer(str.getBytes());
//		替换转换出来的base64字串太长会有\r\n进行换行需要去掉

		rt=StringUtil.replace(rt,"\r", "");
		rt=StringUtil.replace(rt,"\n", "");
		return rt;
	}

	/**
	 * 功能：把base64字串还原
	 * 
	 * @param base64str
	 *            String
	 * @return String 成功还原，失败返回null
	 */
	public static String base642String(String base64str)
	{
		BASE64Decoder base64de = new BASE64Decoder();
		if (base64str.length() == 0)
		{
			return null;
		}
		try
		{
			return new String(base64de.decodeBuffer(base64str));
		}
		catch (IOException e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.base642String("+base64str+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}

	/**
	 * 功能：把base64字串还原
	 * 
	 * @param f
	 *            File
	 * @return String
	 */
	public static String file2base64(File f)
	{
		try
		{
			InputStream fis = new FileInputStream(f);
			byte[] fb = new byte[(int) f.length()];
			fis.read(fb);
			fis.close();
			BASE64Encoder base64en = new BASE64Encoder();
			return base64en.encode(fb);
		}
		catch (IOException e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.file2base64("+f+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}

	/**
	 * 功能：取得虚拟路径mapUrl在操作系统上的实际路径位置

	 * 
	 * @param req
	 *            ServletRequest
	 * @param mapUrl
	 *            String
	 * @return String 成功返回在硬盘的实际位置，失败返回null
	 */
	public static String getServletMappingPath(ServletRequest req, String mapUrl)
	{
		if (req == null || mapUrl == null)
		{
			return null;
		}
		if (mapUrl.trim().length() == 0)
		{
			return null;
		}
		return ((HttpServletRequest) req).getSession().getServletContext()
				.getRealPath(mapUrl);
	}

	/**
	 * 功能：取得虚拟路径mapUrl在操作系统上的实际路径位置

	 * 
	 * @param req
	 *            HttpServletRequest
	 * @param mapUrl
	 *            String
	 * @return String 成功返回在硬盘的实际位置，失败返回null
	 */
	public static String getServletMappingPath(HttpServletRequest req, String mapUrl)
	{
		if (req == null || mapUrl == null)
		{
			return null;
		}
		if (mapUrl.trim().length() == 0)
		{
			return null;
		}
		return req.getSession().getServletContext().getRealPath(mapUrl);
	}

	/**
	 * 功能：把obj对象转换成字串，如果obj是null则返回""串

	 * 
	 * @param obj
	 *            Object
	 * @return String 成功把obj转成字串，否则转成""
	 */
	public static String obj2Str(Object obj)
	{
		if (obj == null)
		{
			return "";
		}
		return obj.toString().trim();
	}

	/**
	 * 功能：判断doubleLanguageStr是否含有中文或小日本文等一个文字含有2个字节的字串
	 * 
	 * @param doubleLanguageStr
	 *            String
	 * @return boolean
	 */
	public static boolean isDoubleByte(String doubleLanguageStr)
	{
		boolean retu = false;
		int len1 = obj2Str(doubleLanguageStr).length();
		if (len1 == 0)
		{
			return retu;
		}
		byte[] bs = doubleLanguageStr.getBytes();
		int len2 = bs.length;
		if (len1 < len2)
		{
			retu = true;
		}
		return retu;
	}
	/**
	 * 计算含有双字节字串的长度
	 * @param str
	 * @return
	 */
	public static int lengthB(String str)
	{
		return str.getBytes().length;
	}
	/**
	 * 将obj(vo)对象转序列化成xml文件
	 * @param obj vo对象
	 * @param xmlname 保存的文件名称

	 */
	public static void object2Xml(Object obj,String xmlname)
	{
		BufferedOutputStream bos=null;
		try
		{
			bos = new BufferedOutputStream(new FileOutputStream(xmlname));
			XMLEncoder xec=new XMLEncoder(bos);
			xec.writeObject(obj);
			xec.close();
		}
		catch (FileNotFoundException e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.object2Xml("+obj+","+xmlname+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}
	/**
	 * 将xml文件转换成vo对象
	 * @param xmlname 转换的xml文件
	 * @return　成功返回vo对象，失败返回null
	 */
	public static Object xml2Object(String xmlname)
	{
		BufferedInputStream bis;
		try
		{
			bis = new BufferedInputStream(new FileInputStream(xmlname));
			XMLDecoder xdd=new XMLDecoder(bis);
			xdd.close();
			return xdd.readObject();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 把xml格式的xmlstr变量转成对象
	 * @param xmlstr
	 * @return 成功返回根据xmlstr的内容构建成一个对象，失败返回null
	 */
	public static Object xmlstr2Object(String xmlstr)
	{
		try
		{
//			String xmlname=(new Date()).getTime()+".xml";
//			File f=new File(xmlname);
//			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
//			String str=new String(xmlstr.getBytes(),"UTF-8");
//			bos.write(str.getBytes());
//			FileInputStream fis=new FileInputStream(f);			
//
//			XMLDecoder xdd=new XMLDecoder(fis);
//			xdd.close();
//			fis.close();
//			bos.close();
//			if(f.exists())
//			{
//				f.delete();
//			}
			ByteArrayInputStream bais=new ByteArrayInputStream(xmlstr.getBytes("UTF-8"));
			XMLDecoder xdd=new XMLDecoder(bais);
			xdd.close();
			return xdd.readObject();
		}
		catch (Exception e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.xmlstr2Object("+xmlstr+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}
	/**
	 * 把obj对象转成xml格式的字串

	 * @param obj
	 * @return 成功返回xml格式的字串，失败返回null
	 */
	public static String object2Xmlstr(Object obj)
	{
		BufferedOutputStream bos=null;
		try
		{
			synchronized(obj)
			{
				String xmlname=(new Date()).getTime()+"";
				File f=new File(xmlname);
				bos = new BufferedOutputStream(new FileOutputStream(f));
				XMLEncoder xec=new XMLEncoder(bos);
				xec.writeObject(obj);
				xec.close();
				FileInputStream fis=new FileInputStream(f);
				byte[] b=new byte[(int)f.length()];
				fis.read(b);
//				String df=new String(retu.getBytes("UTF-8"));
//				bos.write(df.getBytes());
				bos.close();
				fis.close();
				if(f.exists())
				{
					f.delete();
				}
				f=null;
				return new String(b,"UTF-8") ;
			}
		}
		catch (Exception e)
		{
			ExceptionMessageParam emp=new ExceptionMessageParam();
			emp.setKeyOrMessageText("StringUtil.object2Xmlstr("+obj+")出错!");
			emp.setMessage(true);
			throw new SysException(emp,e);
		}
	}
	/**
	 * 把字串数据转换成用","分隔的字串

	 * @param strArray 要转换的字串数组
	 * @return 成功返回字串，失败返回""
	 */
	public static String strArray2Str(String[] strArray)
	{
		String retu="";
		if(strArray!=null)
		{
			for (int i = 0; i < strArray.length; i++)
			{
				retu+=strArray[i]+",";
			}
			retu=StringUtil.trimChr(retu,",");
		}
		return retu;
	}
	

	public static String getLocalResourceStr(String keyName,String resourceName)
	{
		try
		{
			ResourceBundle rb=ResourceBundle.getBundle(resourceName);
			return rb.getString(keyName);
		}
		catch(Exception e)
		{
			return "";
//			log.error("StringUtil.getLocalResourceStr("+keyName+","+resourceName+")出错!",e);
//			ExceptionMessageParam emp=new ExceptionMessageParam();
//			emp.setKeyOrMessageText("StringUtil.getLocalResourceStr("+keyName+","+resourceName+")出错!");
//			emp.setMessage(true);
//			throw new MyFrameworkException(emp,e);
		}
	}
	/**
	 * 
	 * @param charsetName
	 * @param str
	 * @return
	 */
	public static String unicodeStr2AnyCharsetStr(String charsetName,String str)
	{
		Charset chr=Charset.forName(charsetName);
		ByteBuffer bbf=chr.encode(str);
		CharBuffer cb=chr.decode(bbf);
		return cb.toString();
	}
	/**
	 * 把str字串第一个字符转成大写

	 * @param str
	 * @return
	 */
	public static String firstCharToUpperCase(String str)
	{
		String str1=str.substring(0,1).toUpperCase();
		try
		{
			return str1+str.substring(1);
		}
		finally
		{
			str1=null;
		}
	}
	/**
	 * 把str字串第一个字符转成小写

	 * @param str
	 * @return
	 */
	public static String firstCharToLowerCase(String str)
	{
		String str1=str.substring(0,1).toLowerCase();
		try
		{
			return str1+str.substring(1);
		}
		finally
		{
			str1=null;
		}
	}
	/**
	 * 取得cls所在位置的ClassPath起始的根路径
	 * @param cls
	 * @return
	 */
	public static String getRootClassPath(Class cls)
	{
		if(cls==null)
		{
			return null;
		}
		String path=cls.getResource("/").getPath();
		try
		{
			return path;
		}
		finally
		{
			path=null;
		}
	}
	
	public static String getFullValue(String valueStr)
	{
		String  valueStrTemp="";
		int     strlength=0;
				strlength=valueStr.trim().length();
		switch(strlength) 
        { 
        case 1: 
        	valueStrTemp="000000"+valueStr;
        	break; 
        case 2: 
        	valueStrTemp="00000"+valueStr;
        	break; 
        case 3: 
        	valueStrTemp="0000"+valueStr;
        	break;
        case 4: 
        	valueStrTemp="000"+valueStr;
        	break; 
        case 5: 
        	valueStrTemp="00"+valueStr;
        	break; 
        case 6: 
        	valueStrTemp="0"+valueStr;
        	break;         	
        case 7: 
        	valueStrTemp=valueStr;
        	break;         
        default: 
        	valueStrTemp=valueStr;
        } 
		return valueStrTemp;
	}	
	
	public static void main(String[] args)
	{
//		 符号     含义                    表示                示例
//		 ------   -------                 ------------        -------
//		 G        年代标志符              (Text)              AD
//		 y        年                      (Number)            1996
//		 M        月                      (Text & Number)     July & 07
//		 d        日                      (Number)            10
//		 h        时 在上午或下午 (1~12)  (Number)            12
//		 H        时 在一天中 (0~23)      (Number)            0
//		 m        分                      (Number)            30
//		 s        秒                      (Number)            55
//		 S        毫秒                    (Number)            978
//		 E        星期                    (Text)              Tuesday
//		 D        一年中的第几天          (Number)            189
//		 F        一月中第几个星期几      (Number)            2  (2nd Wed in July)
//		 w        一年中第几个星期        (Number)            27
//		 W        一月中第几个星期        (Number)            2
//		 a        上午 / 下午 标记符      (Text)              PM
//		 k        时 在一天中 (1~24)      (Number)            24
//		 K        时 在上午或下午 (0~11)  (Number)            0
//		 z        时区                    (Text)      Pacific Standard Time
//		 '        文本转义符              (Delimiter)
//		 ''       单引号                  (Literal)           '
//		
//		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);
//		try
//		{
//			Date s=sdf.parse("2006-07-24 21:04:43");
//			System.out.println("=="+s.toString());
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
		
//		System.out.println(getLocalResourceStr("domain.datetimeFormat"));
		String s="<input id=\"{$curPageId}\" type=\"hidden\" name=\"pagge.currentPageNo\" value=\"{$curPage}\">";
		System.out.println(StringUtil.replaceRegEx( s,"name=\"page.\\w*\"", "name=\"page.curNo\""));
	}
//	按实际大小(字符大小)返回字符的索引位置

	public static int getRealIdex(String value,int requiredlocation){
		int index=0,icharlen=0;
		for(int m=0;m<value.length();m++){					
			if(value.substring(m, m+1).matches("[\u4e00-\u9fa5]+")){
				icharlen+=2;
			}else{
				icharlen+=1;
			}
			if(icharlen>=requiredlocation||m==value.length()-1) {
				index=m;
				break;
			}
			
		}
		return index;
	}
}
